var liveLocationFeedCommingEvent = new Event();
var liveMediaFeedCommingEvent = new Event();
var passTargetFeedCommingEvent = new Event();

function Event(){
    this.eventHandlers = new Array();
}

Event.prototype.addHandler = function(eventHandler){
    this.eventHandlers.push(eventHandler);
}

Event.prototype.execute = function(args){
    for(var i = 0; i < this.eventHandlers.length; i++){
        this.eventHandlers[i](args);
    }
}

function parseMessage(msg){
    if(msg != null){
        var jsonObject = jQuery.parseJSON(msg);
        if(jsonObject.type == "LiveLocationFeed"){           
            liveLocationFeedCommingEvent.execute(jsonObject);
        }        
        if(jsonObject.type == "LiveMediaFeed"){           
            liveMediaFeedCommingEvent.execute(jsonObject);
        }        
    }
}

function rawInput(data)
{
    log('RECV: ' + data);
}

function rawOutput(data)
{
    log('SENT: ' + data);
}

$(document).ready(function () {
    var connectedEndpoint;
    var callbackAdded = false;

    function callback(response)
    {
        $.atmosphere.log('info', ["response.state: " + response.state]);
        $.atmosphere.log('info', ["response.transport: " + response.transport]);
        if (response.transport != 'polling' && response.state != 'connected' && response.state != 'closed') {
            $.atmosphere.log('info', ["response.responseBody: " + response.responseBody]);
            if (response.status == 200) {
                var data = response.responseBody;
                if (data) {                    
                    parseMessage(data);
                    
                }
            }
        }
    }

    /* transport can be : long-polling, streaming or websocket */
    $.atmosphere.subscribe(STREAMING_SERVICE,
        !callbackAdded? callback : null,
        $.atmosphere.request = {
            transport: 'websocket'
        });
    connectedEndpoint = $.atmosphere.response;
    callbackAdded = true;

});